package com.work.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.work.bean.DiseaseBean;
import com.work.service.IDiseaseService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/disease")
public class DiseaseController {

    @Resource
    private IDiseaseService service;

    public DiseaseBean addDisease;

    public DiseaseController() {
        addDisease = new DiseaseBean();
        addDisease.setDiseasePic("default.jpg");
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @RequestMapping("/show")
    @ResponseBody
    public IPage<DiseaseBean> findByItem(Integer pageNo, Integer pageSize, String DiseaseName, String diseaseSymptom){
        System.out.println(service.findByItem(pageNo, pageSize, DiseaseName, diseaseSymptom));
        return service.findByItem(pageNo,pageSize,DiseaseName,diseaseSymptom);
    }

    @RequestMapping("/addDisease")
    @ResponseBody
    public String addPest(DiseaseBean diseaseBean){
        addDisease.setDiseaseName(diseaseBean.getDiseaseName());
        addDisease.setDiseasePathogeny(diseaseBean.getDiseasePathogeny());
        addDisease.setDiseaseSymptom(diseaseBean.getDiseaseSymptom());
        addDisease.setDiseaseLaw(diseaseBean.getDiseaseLaw());
        addDisease.setDiseaseHarm(diseaseBean.getDiseaseHarm());
        addDisease.setDiseasePrevention(diseaseBean.getDiseasePrevention());


        service.save(addDisease);

        addDisease.setDiseasePic("default.jpg");

        return "success";
    }

    //上传图片
    @RequestMapping("/diseasePic")
    public void pestsAdultPic(MultipartFile file) {
        String res = uploadPic(file);
        addDisease.setDiseasePic(res);
        System.out.println("添加=" + addDisease);

    }
    public String uploadPic(MultipartFile file) {
        String originalName = file.getOriginalFilename();

        assert originalName != null;
        if (!originalName.endsWith(".jpg")) {
            return "error";
        }
        String format = sdf.format(new Date());
        String path = "f:\\forestVue\\forest\\src\\img";
        String realPath = path;
        System.out.println("realPath=" + realPath);
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString() + ".jpg";
        try {
            file.transferTo(new File(folder, newName));
            return newName;
        } catch (IOException e) {
            return e.getMessage();
        }
    }


}
